package com.huoyun.userAdmin.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.huoyun.base.action.BaseAction;
import com.huoyun.base.bean.Result;
import com.huoyun.user.bean.User;
import com.huoyun.user.service.UserService;
import com.huoyun.userAdmin.bean.CheckRealname;
import com.huoyun.userAdmin.service.CheckRealnameService;
import com.huoyun.util.DateUtil;
import com.huoyun.util.FileUtil;
import com.huoyun.util.SendUtil;
import com.huoyun.util.StringUtil;


public class AuthAction extends BaseAction{
	
	private String phone;
	
	private String vcode;
	
	private Result result;
	
	private CheckRealname checkRealname;
	
	/**
	 * 用于管理台得到所有的需要实名验证的用户信息
	 */
	
	private List<CheckRealname> checkRealnameList;
	
	/**
	 * 用户上传的身份证正面照
	 */
	private File positiveFile;
	
	/**
	 * 用户上传的身份证正面照文件名称
	 */
	private String positiveFileFileName;
	
	/**
	 * 用户上传的身份证背面照
	 */
	private File backFile;
	
	/**
	 * 用户上传的身份证背面照文件名称
	 */
	private String backFileFileName;
	
	private UserService userService;
	
	private CheckRealnameService checkRealnameService;
	
	
	public String email;
	public String passwd;
	
    private MimeMessage mimeMsg; // MIME邮件对象

    private Session session; // 邮件会话对象

    private Properties props; // 系统属性

    private boolean needAuth = false; // smtp是否需要认证

    private String username = ""; // smtp认证用户名和密码

    private String password = "";

    private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成
    
    public AuthAction() {

    }
    
    public String preAuthPhone()
    {
    	return SUCCESS;
    }
    
    public String authPhone()
    {
    	String correntVcode = (String)getSession().getAttribute("phoneCode");
    	String correntPhone = (String)getSession().getAttribute("userPhone");
    	
    	if(StringUtils.isNotEmpty(correntVcode) && StringUtils.isNotEmpty(correntPhone))
    	{
    		if(correntVcode.equals(vcode) && correntPhone.equals(phone))
    		{
    			User user = getLoginUser();
    			
    			//更新当前session中的用户信息
    			user.setCheckMobilePhone(true);
    			user.setMobilePhone(phone);
    			
    			//更新数据库中用户的信息
    			userService.updateMobilePhoneByUserId(user.getId(), phone);
    			
    			this.setResultMsg("您的手机号码（" + phone + "）已经被认证通过！");
    			
    			return SUCCESS;
    		}
    		else
    		{
    			this.setResultMsg("您输入的校验码错误，请重新获取！");
    			return ERROR;
    		}
    	}
    	else
    	{
    		this.setResultMsg("您的校验码已经过期，请重新获取！");
    		return INPUT;
    	}
    }
    
    public String sendCode()
    {
    	result = new Result();
    	
    	if(StringUtils.isEmpty(phone))
    	{
    		result.setResult(Result.ERROR);
    		result.setMessage("请输入正确的手机号码。");
    		return ERROR;
    	}
    	
    	//随机生成一个六位的只有数字的手机验证码
    	String randCode = RandomStringUtils.random(6, false, true);
    	
    	try
    	{
	    	//调用短信发送接口给用户手机发短信
	    	String sendResult = SendUtil.sendSMS(phone, "感谢你进行货运网手机认证，验证码为：" + randCode + "[货运网]");
	    	//发送成功
	    	if("100".equals(sendResult))
	    	{
	    		//将生成的手机验证码放到当前的session中，以用来验证用户输入的手机验证码是否正确
	        	getSession().setAttribute("phoneCode", randCode);
	        	getSession().setAttribute("userPhone", phone);
	    		
	        	result.setResult(Result.SUCCESS);
	        	result.setMessage("验证码已经成功发送，请注意查收(验证码为："+ randCode +")。");
	    	}
	    	else if("112".equals(sendResult))
	    	{
	    		result.setResult(Result.ERROR);
	    		result.setMessage("你输入的号码不存在，请重新发送。");
			}
	    	else
	    	{
	    		result.setResult(Result.ERROR);
	    		result.setMessage("验证码发送失败，请重新发送。");
	    	}
    	}
    	catch (Exception e) {
    		result.setResult(Result.ERROR);
    		result.setMessage("验证码发送失败，请重新发送。");
		}

    	return SUCCESS;
    }
    public String preAuthNameAdmin(){
    	
    	return SUCCESS;
    }
    
    public String authNameAdmin(){
    	
    	return SUCCESS;
    }
    
	public String preAuthName()
	{
		try
		{
			checkRealname = checkRealnameService.getCheckRealnameByUserId(getLoginUser().getId());
			
			if(checkRealname != null)
			{
				if(checkRealname.getStatus() == CheckRealname.STATUS_WAITING)
				{
					this.setResultMsg("您的实名认证申请已经提交，请耐心等到网站的审核！");
					return "prompt";
				}
				else if(checkRealname.getStatus() == CheckRealname.STATUS_PASS)
				{
					this.setResultMsg("您的实名认证申请已经通过了网站的审核！");
					return "prompt";
				}
				else
				{
					this.setResultMsg("您的实名认证申请没有通过网站的审核，请再次核对相应信息的正确性！");
				}
			}
		}
		catch (Exception e) {
			e.fillInStackTrace();
		}
		return SUCCESS;
	}
	
	public String authName()
	{
		String path = FileUtil.UPLOAD_CARD_DIR + "/" + DateUtil.getCurrentDate();
		String saveFolderPath = ServletActionContext.getRequest().getRealPath(path);  
		
		File saveFolder = new File(saveFolderPath);
		
		if (!saveFolder.exists())
		{
			saveFolder.mkdir();
		}
		File savePositiveFile = new File(saveFolderPath, UUID.randomUUID().toString() + "." + StringUtil.getLastName(positiveFileFileName)); 
		File saveBackFile = new File(saveFolderPath, UUID.randomUUID().toString() + "." + StringUtil.getLastName(backFileFileName)); 		
		
		try {
			FileUtil.copyFile(positiveFile, savePositiveFile);
			FileUtil.copyFile(backFile, saveBackFile);
			
			checkRealname.setCardPositiveFile(path + "/" + savePositiveFile.getName());
			checkRealname.setCardBackFile(path + "/" + saveBackFile.getName());
		} catch (Exception e) {
			this.setResultMsg("文件上传失败！");
		}
		
		try
		{
			//待审核状态
			checkRealname.setStatus(-1);
			
			//如果是更新实名认证申请的信息
			if(checkRealname.getId() != 0)
			{
				checkRealnameService.update(checkRealname);
			}
			else
			{
				checkRealname.setUserId(getLoginUser().getId());
				checkRealnameService.saveCheckRealname(checkRealname);
			}
			
			this.setResultMsg("您的实名认证申请已经提交成功，请耐心等到网站的审核！");
		}
		catch (Exception e) {
			this.setResultMsg("您的实名认证申请提交失败，请稍后再试！");
			e.fillInStackTrace();
			
		}

		return SUCCESS;
	}
	
	public String preAuthEmail()
	{
		return SUCCESS;
	}
	
	public String authEmail()
	{
		if(SendUtil.sendAuthEmail(email, getLoginUser().getUsername()))
		{
			//发送成功
			return SUCCESS;
		}
		else
		{
			//发送失败
			return ERROR;
		}
	}
	
	public String authEmailResult()
	{
		this.setResultMsg("您的邮箱地址已经通过了网站的认证！");
		
		return SUCCESS;
	}

	
    public AuthAction(String smtp) {
        setSmtpHost(smtp);
        createMimeMessage();
    }

    public void setSmtpHost(String hostName) {
        System.out.println("设置系统属性：mail.smtp.host = " + hostName);
        if (props == null)
            props = System.getProperties(); // 获得系统属性对象
        props.put("mail.smtp.host", hostName); // 设置SMTP主机
    }

    public boolean createMimeMessage() {
        try {
            System.out.println("准备获取邮件会话对象！");
            session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
        } catch (Exception e) {
            System.err.println("获取邮件会话对象时发生错误！" + e);
            return false;
        }
        System.out.println("准备创建MIME邮件对象！");
        try {
            mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
            mp = new MimeMultipart(); // mp 一个multipart对象
            // Multipart is a container that holds multiple body parts.
            return true;
        } catch (Exception e) {
            System.err.println("创建MIME邮件对象失败！" + e);
            return false;
        }
    }

    public void setNeedAuth(boolean need) {
        System.out.println("设置smtp身份认证：mail.smtp.auth = " + need);
        if (props == null)
            props = System.getProperties();
        if (need) {
            props.put("mail.smtp.auth", "true");
        } else {
            props.put("mail.smtp.auth", "false");
        }
    }

    public void setNamePass(String name, String pass) {
        System.out.println("程序得到用户名与密码");
        username = name;
        password = pass;
    }

    public boolean setSubject(String mailSubject) {
        System.out.println("设置邮件主题！");
        try {
            mimeMsg.setSubject(mailSubject);
            return true;
        } catch (Exception e) {
            System.err.println("设置邮件主题发生错误！");
            return false;
        }
    }

    public boolean setBody(String mailBody) {
        try {
            System.out.println("设置邮件体格式");
            BodyPart bp = new MimeBodyPart();
            // 转换成中文格式
            bp.setContent(
                    "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"
                            + mailBody, "text/html;charset=GB2312");
            mp.addBodyPart(bp);
            return true;
        } catch (Exception e) {
            System.err.println("设置邮件正文时发生错误！" + e);
            return false;
        }
    }

    public boolean setFrom(String from) {
        System.out.println("设置发信人！");
        try {
            mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean setTo(String to) {
        System.out.println("设置收信人");
        if (to == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
                    .parse(to));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean setCopyTo(String copyto) {
        System.out.println("发送附件到");
        if (copyto == null)
            return false;
        try {
            mimeMsg.setRecipients(Message.RecipientType.CC,
                    (Address[]) InternetAddress.parse(copyto));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean sendout() {
        try {
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            System.out.println("正在发送邮件....");
            Session mailSession = Session.getInstance(props, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String) props.get("mail.smtp.host"), username,
                    password);
            transport.sendMessage(mimeMsg, mimeMsg
                    .getRecipients(Message.RecipientType.TO));
            // transport.send(mimeMsg);
            System.out.println("发送邮件成功！");
            transport.close();
            return true;
        } catch (Exception e) {
            System.err.println("邮件发送失败！" + e);
            return false;
        }
    }
	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	//lipeng 
	public String getPaswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String preAuthEmial()
	{
		return SUCCESS;
	}
	
	public String authEamil()

	{
		boolean  sendresult;
		String wc ="";
        List list = new ArrayList(); 
        // list.add(1); 
        for (int i = 0; i < 10; i++) 
                list.add(i+"");

        for (char c = 'a'; c <= 'z'; c++) 
                list.add(c+""); 
        for (char c = 'A'; c <= 'Z'; c++) 
            list.add(c+"");

        String randomStr = ""; 
       
        for (int i = 0; i < 8; i++) { 
                int mathInt; 
                mathInt=(int) (Math.random()*list.size()); 
                randomStr +=(String)list.get(mathInt); 
                list.remove(mathInt); 
        }

        Random r=new Random();
        for(int a=0;a<9;a++){
            String i=String.valueOf(r.nextInt(10));
            wc+=i;
        }
        String mailbody = "<font size=5 >你的邮箱认证已经通过</font><br>您的密码是："+randomStr+"<br>请您及时输入验证码进登录网站进行邮箱验证验证，感谢你使用本系统！</font>";
        AuthAction themail = new AuthAction("smtp.sohu.com");
        themail.setNeedAuth(true);
        // 标题
        themail.setSubject("邮箱认证码，请勿回复");

        // 邮件内容 支持html 如 <font color=red>欢迎你,java</font>
        themail.setBody(mailbody);
        // 收件人邮箱
        themail.setTo(email);
        
        
        // 发件人邮箱
        themail.setFrom("lptg86@sohu.com");

        themail.setNamePass("lptg86@sohu.com", "kobe86"); // 用户名与密码,即您选择一个自己的电邮
// TODO       sendresult=themail.sendout();
        sendresult = true;
        if (sendresult== false)
        	 return "error";
        
        else if  (sendresult == true)
        {	
        
            System.out.println("验证码是:"+ randomStr);
            
            HttpSession session = ServletActionContext.getRequest().getSession();
            session.setAttribute("randomStr", randomStr);
            
            
//            if( randomStr == passwd)
//            {
//        	 System.out.println("邮箱验证成功！");
//        	// return SUCCESS;
//        	
//            }
            System.out.println(ServletActionContext.getRequest().getSession().getAttribute("randomStr"));

        }
		return SUCCESS;
        
		
//		return null;
	}
	
	public String authPasswd(){
		
		System.out.println("authPasswd.....");
		System.out.println(ServletActionContext.getRequest().getSession().getAttribute("randomStr"));
		
      if( ServletActionContext.getRequest().getSession().getAttribute("randomStr").toString().trim().equals(passwd.trim()) )
      {
    	  System.out.println("邮箱验证成功！");
  	
      }
      else{
    	  
    	  return "error";
      }
      //把结果写入 servlet response 的流中 
      
		
		return SUCCESS;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	public String getVcode() {
		return vcode;
	}

	public void setVcode(String vcode) {
		this.vcode = vcode;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public CheckRealnameService getCheckRealnameService() {
		return checkRealnameService;
	}

	public void setCheckRealnameService(CheckRealnameService checkRealnameService) {
		this.checkRealnameService = checkRealnameService;
	}

	public CheckRealname getCheckRealname() {
		return checkRealname;
	}

	public void setCheckRealname(CheckRealname checkRealname) {
		this.checkRealname = checkRealname;
	}

	public File getPositiveFile() {
		return positiveFile;
	}

	public void setPositiveFile(File positiveFile) {
		this.positiveFile = positiveFile;
	}

	public String getPositiveFileFileName() {
		return positiveFileFileName;
	}

	public void setPositiveFileFileName(String positiveFileFileName) {
		this.positiveFileFileName = positiveFileFileName;
	}

	public File getBackFile() {
		return backFile;
	}

	public void setBackFile(File backFile) {
		this.backFile = backFile;
	}

	public String getBackFileFileName() {
		return backFileFileName;
	}

	public void setBackFileFileName(String backFileFileName) {
		this.backFileFileName = backFileFileName;
	}

}
